// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        textureNum:4,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {

    },

    addMaterial(material,node){

        if(node instanceof cc.MultiSprite){
            if(!this.materials){
                this.materials = []
            }
            let isAdd = true
            for(let i=0;i<this.materials.length;i++){
                let curretn = this.materials[i]
                if(curretn == material){
                    isAdd = false
                }
            }
            if(isAdd){
                this.materials.push(material)
            }
            for(let i=0;i<this.materials.length;i++){
                let curretn = this.materials[i]
                if(curretn){
                    if(this.textures){
                        for(let k=0;k<this.textures.length;k++){
                            let textureInfo = this.textures[k]
                            if(textureInfo){
                                curretn.setProperty('texture'+k, textureInfo.texture);
                                if(textureInfo.sprite == node){
                                    node.textureIdx = k
                                }
                            }
                        }
                    }
                }
            }
        }

    },
    

    addTexture(texture,material,sprite){

        if(texture && texture instanceof cc.Texture2D && texture.loaded && sprite && sprite instanceof cc.MultiSprite){
            if(!this.textures){
                this.textures = []
            }
            let isAdd = true
            let uuid = texture._uuid
            for(let i=0;i<this.textureNum;i++){
                if(i < this.textures.length && this.textures[i].texture._uuid == uuid){
                    isAdd = false
                    this.textures[i] = {texture:texture,sprite:sprite}
                }
                if(i>=this.textures.length){
                    break
                }
            }
            if(isAdd){
                if(this.textureNum > this.textures.length){
                    this.textures.push({texture:texture,sprite:sprite})
                }else{
                    material.setProperty('texture0', texture);
                    sprite.textureIdx = 0
                }
            }
        }

        
        
    }
    

    // update (dt) {},
});
